package com.hxut.controller;

import com.hxut.dao.UserDao;
import com.hxut.domain.QueryInfo;
import com.hxut.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description: UserController
 * date: 2022/6/16 8:52
 * author: MR.孙
 */
@RestController
public class UserController {
    @Autowired
    private UserDao userDao;
    @GetMapping("/alluser")
    public Map<String,Object> getAllUser(QueryInfo queryInfo){
        HashMap<String,Object> userMap=new HashMap<>();
        int userCounts = userDao.getUserCounts("%"+queryInfo.getQuery()+"%");
        int pageStart=(queryInfo.getPageNum()-1)*queryInfo.getPageSize();//当前起始的索引，等于)当前页的页数-1)*总数据数
        List<User> allUser = userDao.getAllUser("%" + queryInfo.getQuery() + "%", pageStart, queryInfo.getPageSize());
        System.out.println("总条数->"+userCounts);
        userMap.put("numbers",userCounts);
        userMap.put("data",allUser);
        return userMap;
    }

    @PutMapping("/userstate/{id}/{state}")
    public String updateState(@PathVariable("id") Integer id, @PathVariable("state") Boolean state ){
        int i = userDao.updateState(id, state);
        String msg=i>0?"success":"error";
        return msg;
    }

    @PostMapping("/addUser")
    public String insertUser(@RequestBody User user){
        //需要管理员审核后才能把状态改为true，初始状态普通用户
        user.setRole("普通用户");
        user.setState(false);
        int i = userDao.insertUser(user);
        return i>0?"success":"error";

    }

    @DeleteMapping("/deluser/{id}")
    public String deleteUser (@PathVariable Integer id){
        int i = userDao.deleteUser(id);
        return i>0?"success":"error";
    }

    @PutMapping("/editUser")
    public String editUser(@RequestBody User user){
        int i = userDao.updateUser(user);
        return i>0?"success":"error";
    }

}
